//
// Created by HP on 2025/11/17.
//

#include "Sale.h"
#include <iostream>

Sale::Sale() : Model("sales") {
    setTableDefault("ticketId", "INT NOT NULL");
    setTableDefault("userId", "INT NOT NULL");
    setTableDefault("orderId", "INT");
    setTableDefault("saleTime", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
    setTableDefault("createdAt", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
}

void Sale::bind(const std::string& key, const std::string& value) {
    if (!TableCols.count(key)) {
        std::cerr << "Error: Invalid key for sale bind" << std::endl;
        return;
    }
    if (TableCols[key].find("UNIQUE") == std::string::npos && key != "id") {
        std::cerr << "Error: Key is not unique for sale bind" << std::endl;
        return;
    }

    std::string selectSql = "SELECT * FROM " + TableName + " WHERE " + key + " = '" + Model::escapeSqlLiteral(value) + "';";
    std::vector<std::map<std::string, std::string>> result = DBConnector::getInstance()->query(selectSql);

    if (result.empty()) {
        std::cerr << "bind failed: SQL execution error or no result. SQL: " << selectSql << std::endl;
        return;
    }

    std::cout << "bind success. Table: " << TableName << std::endl;

    if (result.size() > 1) {
        std::cerr << "Error: Multiple sales found with the same " << key << std::endl;
        return;
    } else if (result.size() == 1) {
        this->id = result[0]["id"];
        this->ticketId = result[0]["ticketId"];
        this->userId = result[0]["userId"];
        this->orderId = result[0].count("orderId") > 0 ? result[0]["orderId"] : "";
        this->saleTime = result[0]["saleTime"];
        this->createdAt = result[0]["createdAt"];
    }
}

bool Sale::save() {
    std::string createSaleSql = "INSERT INTO " + TableName + " (ticketId, userId";
    std::string valuesSql = " VALUES (" + ticketId + ", " + userId;
    
    if (!orderId.empty()) {
        createSaleSql += ", orderId";
        valuesSql += ", " + orderId;
    }
    
    if (!saleTime.empty()) {
        createSaleSql += ", saleTime";
        valuesSql += ", '" + Model::escapeSqlLiteral(saleTime) + "'";
    }
    
    createSaleSql += ")";
    valuesSql += ");";
    
    std::string fullSql = createSaleSql + valuesSql;
    int executeCode = DBConnector::getInstance()->execute(fullSql);
    if (executeCode == -1) {
        std::cerr << "create sale failed: SQL execution error. SQL: " << fullSql << std::endl;
        return false;
    } else {
        std::cout << "create sale success. Table: " << TableName << std::endl;
        return true;
    }
}
